package com.yishusmt.wechatapi.wechatdev.utils;

import com.yishusmt.wechatapi.wechatdev.constant.RedisConstant;
import com.yishusmt.wechatapi.wechatdev.constant.WeChatConstant;
import com.yishusmt.wechatapi.wechatdev.entity.AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 *  获取微信access_token
 *
 * @author zhangyi
 * @date 2018/8/28 9:38
 */
@Component
public class AccessTokenUtil {

    @Autowired
    private HttpClientUtil httpClientUtil;

    @Autowired
    private RedisUtil redisUtil;

    public AccessToken getAccessToken(){
        String url = WeChatConstant.WECHAT_URL
                .replace("APPID", WeChatConstant.APPID)
                .replace("APPSECRET", WeChatConstant.SECRET);
        String connect = null;
        AccessToken accessToken = null;
        String  access = redisUtil.get(RedisConstant.WECHAT_ACCESS_TOKEN);
        if(access != null){
            accessToken = new AccessToken();
            accessToken.setAccess_token(access);
            return accessToken;
        }else{
            try {
                connect  = httpClientUtil.getConnect(url);
                accessToken = JacksonUtil.readValue(connect, AccessToken.class);
                redisUtil.set(RedisConstant.WECHAT_ACCESS_TOKEN,accessToken.getAccess_token()
                        ,new Long(7100));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return accessToken;
        }
    }
}
